<?php

namespace App\Services;

use App\Models\Bank;
use App\Models\UserBank;
use common\utils\SysCode;

class BankService
{
    const DISABLE = 0; // 停用
    const ENABLE = 1;  // 启用
    const DELETE = 2;  // 删除

    public static function all()
    {
        return Bank::where(['status' => 1])->get()->toArray();
    }

    // 获取用户银行列表
    public static function userBank($user_id, $status = self::ENABLE)
    {
        return UserBank::where(['user_id' => $user_id, 'status' => $status])->get();
    }

    // 新增银行卡
    public static function addUserBank($user_id, $params)
    {
        $ub = UserBank::where(['user_id' => $user_id, 'bank_id' => $params['bank_id'], 'card' => $params['card']])->first();
        if ($ub) {
            // 已删除的银行卡，恢复启用
            if ($ub->status == self::DELETE) {
                $ub->status = self::ENABLE;
            } else {
                // 银行卡已存在
                error_exit(SysCode::USER_BANK_EXIST, ['card' => $params['card']]);
            }
        } else {
            $ub = new UserBank($params);
            $ub->user_id = $user_id;
        }
        $ub->save();
        return $ub;
    }

    public static function delUserBank($user_id, $id)
    {
        $ub = UserBank::where(['id' => $id, 'user_id' => $user_id])->where('status', '<>', self::DELETE)->first();
        if (!$ub) {
            error_exit(SysCode::INVALID_ARGUMENT);
        }
        $ub->status = self::DELETE;
        $ub->save();
        return 0;
    }
}
